var prefix = "/sales/order";
$(function () {
    load();
});
$('#workOrderTable').on('load-success.bs.table', function (e, data) {
    if (data.total && !data.rows.length) {
        $('#workOrderTable').bootstrapTable('selectPage').bootstrapTable('refresh');
    }
});

function load() {
    $('#workOrderTable').bootstrapTable(
        {
            method: 'get', // 服务器数据的请求方式 get or post
            url: prefix + "/list", // 服务器数据的加载地址
            showRefresh: true,
            // showToggle : true,
            iconSize: 'outline',
            // toolbar: '#exampleToolbar',
            striped: true, // 设置为true会有隔行变色效果
            dataType: "json", // 服务器返回的数据类型
            pagination: true, // 设置为true会在底部显示分页条
            pageList: [10, 20, 50],
            // queryParamsType : "limit",
            // //设置为limit则会发送符合RESTFull格式的参数
            singleSelect: false, // 设置为true将禁止多选
            // contentType : "application/x-www-form-urlencoded",
            // //发送到服务器的数据编码类型
            pageSize: 10, // 如果设置了分页，每页数据条数
            pageNumber: 1, // 如果设置了分布，首页页码
            // search : true, // 是否显示搜索框
            showColumns: true, // 是否显示内容下拉框（选择显示的列）
            sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者
            // "server"
            queryParams: function (params) {
                return {
                    limit: params.limit,
                    offset: params.offset,
                    order: 'desc',
                    queryItem: $.trim($('#queryItem').val()),
                    payTimeStart: $('#payTimeStart').val(),
                    payTimeEnd: $('#payTimeEnd').val(),
                    start: $('#start').val(),
                    end: $('#end').val(),
                    status: $('#status').val(),
                    centreId: $("*[name='centreId']").val(),
                    supplyName:$("#supplyName").val()
                };
            },
            rowStyle:function(row,index) {
                if (row.status == 1 || row.status == 0) {
                    if (row.isUptime == 1) {
                        return {css: {'background-color': 'yellow'}};
                    }else {
                        return {css: {'background-color': ''}};
                    }
                }else {
                    return {css: {'background-color': ''}};
                }
            },
            // //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
            // queryParamsType = 'limit' ,返回参数必须包含
            // limit, offset, search, sort, order 否则, 需要包含:
            // pageSize, pageNumber, searchText, sortName,
            // sortOrder.
            // 返回false将会终止请求
            columns: [
                {
                    title: '序号',// 列标题
                    formatter: function (value, row, index) {
                        var pageSize = $('#workOrderTable').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                        var pageNumber = $('#workOrderTable').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                        return pageSize * (pageNumber - 1) + index + 1;
                    }
                },
                {
                    field: 'city', // 列字段名
                    title: '订单区域',
                    formatter: function (value, row, index) {
                        return '<b>' + value+ '</b>'
                    }
                },
                {
                    field: 'nums', // 列字段名
                    title: '售后数量',// 列标题
                    formatter: function (value, row, index) {
                        return '<b>' + value+ '</b>'
                    }
                },
                {
                    field: 'typename', // 列字段名
                    title: '工单类型',
                    formatter: function (value, row, index) {
                        return '<b>' + value+ '</b>'
                    }
                },
                {
                    field: 'cause', // 列字段名
                    title: '工单原因',
                    formatter: function (value, row, index) {
                        return '<b>' + value+ '</b>'
                    }
                },
                {
                    field: 'createTime', // 列字段名
                    title: '工单信息',
                    formatter: function (value, row, index) {
                        var info = "";
                        if (value) {
                            info = info + '<p>' + "创建时间:" + value + '</p>'
                        }
                        if (row.worksn) {
                            info = info + '<p>' + "工单号:" + row.worksn + '</p>'
                        }
                        info = info + '<p>' + "门店/ID:" + row.realname + '/'+ row.mid  + '</p>'
                        if (row.mobile) {
                            info = info +  '<p>' + "门店手机:" + row.mobile + '</p>'
                        }
                        if (row.upRealname) {
                            info = info + '<p>' + "上级门店/ID:" + row.upRealname + '/'+ row.upMid  + '</p>'
                        }
                        if (row.tXiaoqu) {
                            info = info +  '<p>' + "所属小区:" + row.tXiaoqu + '</p>'
                        }
                        return info;
                    }
                },
                {
                    field: 'ogid', // 列字段名
                    title: '商品信息',
                    formatter: function (value, row, index) {
                        var info = "";
                        if (row.ordersn) {
                            info = info + '<p>' + "订单编号:" + row.ordersn + '</p>'
                        }
                        if (row.ogid) {
                            info = info + '<p>' + "订单商品编号:" + row.ogid + '</p>'
                        }
                        if (row.goodscode) {
                            info = info + '<p>' + "商品编号:" + row.goodscode + '</p>'
                        }
                        if (row.supplyName) {
                            info = info + '<p>' + "供应商:" + row.supplyName + '</p>'
                        }
                        info = info + '<p>' +  row.shortTitle + '</p>';
                        if (row.thumb) {
                            var targetSrc = null;
                            if (row.thumb.indexOf("http") >= 0 || row.thumb.indexOf("https") >= 0) {
                                targetSrc = row.thumb;
                            } else {
                                var definePrefix = $('#definePrefix').val();
                                targetSrc = definePrefix + row.thumb
                            }
                            info = info + '<p>' + '<img style="width:50px;height:50px;" src=' + targetSrc + '>' + '</p>'
                        }
                        info = info
                            + '<p>'
                            + '<span>'+ "成本价:"+ row.costprice+'</span>'
                            + '<span>'+ "运费:"+ row.dispatchprice+'</span>'
                            + '<span>'+ "应付价:"+ row.marketprice+'</span>'
                            + '<span>'+ "数量:"+ row.total+'</span>'
                            + '<span>'+ "总价:"+ row.price+'</span>'
                            + '</p>';
                        info = info + '<p>' + "上架时间段:" + row.upStartTime + '——'+ row.upEndTime+'</p>'
                        return info;
                    }
                },
                {
                    field: 'saddress', // 列字段名
                    title: '下单信息',
                    formatter: function (value, row, index) {
                        var info="";
                        info = info
                            + '<p>' + "送货地址:"+ value + '</p>'
                            +'<p>' + "运送车次:"+ row.carName + '</p>'
                            + '<p>' + "下单人:"+ row.nickname + '</p>'
                            + '<p>' + "收货人:"+ row.sname + '</p>'
                            + '<p>' + "手机号:"+ row.sMobile + '</p>';
                        return info;
                    }
                },
                {
                    field: 'money', // 列字段名
                    title: '退款金额信息',
                    formatter: function (value, row, index) {
                        var info = '<p>' + "所退总金额:"+ value + '</p>'
                        + '<p>' + "退至微信:"+ row.paymoney + '</p>'
                        + '<p>' + "退至余额:"+ row.credit2money + '</p>'
                        // +  '<p>' + "扣门店佣金:"+ row.commissionMoney + '</p>'
                        // +  '<p>' + "扣上级门店佣金:"+ row.upCommissionMoney + '</p>'
                       return info;
                    }
                },
                {
                    field: 'contents', // 列字段名
                    title: '工单内容',
                    width: '12%'
                },
                {
                    field: 'pic', // 列字段名
                    title: '工单图片',
                    formatter: function (value, row, index) {
                        var _source="";
                        if (value) {
                            var _picList = value.split(",");
                            for (var i=0;i< _picList.length ;i++) {
                                var item = _picList[i];
                                if (item) {
                                    if (item.indexOf("http") >= 0 || item.indexOf("https") >= 0) {

                                    } else {
                                        var definePrefix = $('#definePrefix').val();
                                        item = definePrefix + item
                                    }
                                    _source = _source + '<a target="_blank" href= '+ item+'>' + '<img style="width:50px;height:50px;" onmouseenter="bigpic(this)" onmouseleave="oldpic(this)" src=' + item + '>' +'</a>'
                                }
                            }
                            return _source;
                        }
                    }
                },
                {
                    field: 'isreply',
                    title: '回复状态',
                    formatter: function (value, row, index) {
                        if (value == 1) {
                            return '已回复'
                        }
                        return '未回复'
                    }
                },
                {
                    field: 'status',
                    title: '处理状态',
                    formatter: function (value, row, index) {
                        if (value == -1) {
                            return '关闭工单'
                        } else if (value == 0) {
                            return '未处理'
                        }else if (value == 1) {
                            return '财务处理'
                        }else if (value == 2){
                            return '已完成'
                        }else {

                        }
                    }
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (row.status == 0) {
                            var r = '<a class="btn btn-success btn-xs ' + s_reply_h + '" href="#" title="回复"  mce_href="#" onclick="reply(\'' + value + '\')"><i class="fa fa-envelope-o"></i></a>';
                            var f = '<a class="btn btn-info btn-xs ' + s_forward_h + '" href="#" title="转财务"  mce_href="#" onclick="forwardCaiWu(\'' + value + '\')"><i class="fa fa-mail-reply-all"></i></a>';
                            var c = '<a class="btn btn-primary btn-xs ' + s_close_h + '" href="#" title="关闭"  mce_href="#" onclick="closeWorkOrder(\'' + value + '\')"><i class="fa fa-ban"></i></a>';
                            var d = '<a class="btn btn-warning btn-xs ' + s_remove_h + '" href="#" title="删除"  mce_href="#" onclick="remove(\'' + value + '\')"><i class="fa fa-remove"></i></a>';
                            return r +'<br>'+ f+ '<br>'+c+ '<br>'+d;
                        }else if (row.status == 2) {
                            return '<a class="btn btn-success btn-xs ' + s_reply_h + '" href="#" title="回复"  mce_href="#" onclick="replyRead(\'' + value + '\')"><i class="fa fa-envelope-o"></i></a>';
                        }

                    }
                }],
                onPostBody: function(){
                	sumCash();
				}
        });
}
/**
 * 客服关闭工单
 */
function closeWorkOrder(workId) {
    layer.open({
        id: 'close_work_order',
        type: 2,
        title: '关闭工单',
        maxmin: true,
        shadeClose: false,
        area: ['60%', '80%'],
        content: '/sales/order/closeWorkOrder/'+ workId
    });
}
/**
 * 转财务处理页面
 */
function forwardCaiWu(workId) {
    layer.open({
        id: 'forward_cw_order',
        type: 2,
        title: '转财务处理',
        maxmin: true,
        shadeClose: false,
        area: ['60%', '80%'],
        content: '/sales/order/forwardCw/'+ workId
    });
}

function sumCash() {
	var order =  'desc';
	var queryItem = $.trim($('#queryItem').val());
	var payTimeStart = $('#payTimeStart').val();
	var   payTimeEnd = $('#payTimeEnd').val();
	var start = $('#start').val();
	var  end = $('#end').val();
	var status = $('#status').val();
	var  centreId = $("*[name='centreId']").val();
     $.ajax({
         url: prefix+"/sumWorkMoney",
         data:{
             "order":order,"queryItem":queryItem,"payTimeStart":payTimeStart,"payTimeEnd":payTimeEnd,"start":start,
             "end":end,"status":status,"centreId":centreId},
         dataType: "json",
         success: function(data){
             if(data){
             	if(data.sumMoney!=''){
                     $("#sumMoney").val(data.sumMoney);
					}else{
                     $("#sumMoney").val("0");
					}

             }
         }
     })
}


function reLoad() {
    $('#workOrderTable').bootstrapTable('refresh');
}
function remove(workId) {
    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/remove",
            type: "post",
            data: {
                'workId': workId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}


function bigpic(obj) {
    var wValue=3 * $(obj).width();
    var hValue=3* $(obj).height();
    $(obj).stop().animate({width: wValue,
        height: hValue,
        left:("-"+(0.5 * $(obj).width())/2),
        top:("-"+(0.5 * $(obj).height())/2)}, 1000);
}
function oldpic(obj){
    $(obj).stop().animate({width: "60",
        height:"100",
        left:"0px",
        top:"0px"}, 1000 );
}

/**
 * 查看回复，带提交
 * @param workId
 */
function reply(workId) {
    layer.open({
        id: 'work_reply',
        type: 2,
        title: '查看回复',
        maxmin: true,
        shadeClose: false,
        area: ['70%', '90%'],
        content: prefix + '/reply/' + workId // iframe的url
    });
}

/**
 * 查看回复，无提交
 * @param workId
 */
function replyRead(workId) {
    layer.open({
        id: 'work_reply_read',
        type: 2,
        title: '查看回复',
        maxmin: true,
        shadeClose: false,
        area: ['70%', '90%'],
        content: prefix + '/replyRead/' + workId // iframe的url
    });
}

function saveOutTime() {
    $.ajax({
        url: prefix + "/saveOutTime",
        type: "post",
        data: {
            'outTime': $('#outTime').val()
        },
        beforeSend: function (request) {
            index = layer.load();
        },
        success: function (r) {
            if (r.code == 0) {
                layer.close(index);
                layer.msg(r.msg);
            } else {
                layer.msg(r.msg);
            }
        }
    });
}

/**
 * 导出供应商excel
 */
function exportWorkOrders() {
    var queryItem = $.trim($('#queryItem').val());
    var start = $('#start').val();
    var end = $('#end').val();
    var status = $('#status').val();
    var centreId = $("*[name='centreId']").val();
    var payTimeStart =  $('#payTimeStart').val();
    var payTimeEnd = $('#payTimeEnd').val();
    var supplyName=$("#supplyName").val()
    window.location.href = prefix + "/exportWorkOrders?queryItem="+ queryItem +"&centreId="+ centreId
    +"&start="+start +"&end="+ end +"&status="+ status + "&payTimeStart="+payTimeStart+"&payTimeEnd="+payTimeEnd+"&supplyName="+supplyName
}